<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="板块名称" prop="name">
      <el-input v-model="dataForm.name" placeholder="板块名称"></el-input>
    </el-form-item>
    <el-form-item label="板块图片" prop="listImg" >
      <el-upload
        class="avatar-uploader"
        :action="uploadUrl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :on-error="handleAvatarError">
        <img v-if="dataForm.listImg" :src="dataForm.listImg" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>
    <el-form-item label="所属分类" prop="categoryId">

      <el-select v-model="dataForm.categoryId" placeholder="请选择">
        <el-option
          v-for="item in categoryList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
          >
        </el-option>
      </el-select>
    </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="dataForm.sort" controls-position="right" :min="0" label="排序"></el-input-number>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="dataForm.status" active-value="1" inactive-value="0"
                   active-color="#13ce66" inactive-color="#ff4949">
        </el-switch>
      </el-form-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        //图片上传地址
        uploadUrl:'',
        //上传成功返回的地址
        imageUrl: '',
        //社区分类列表
        categoryList:[],
        //社区分类id
        categoryId:'',
        //此弹窗控制
        visible: false,
        //提交表单的数据
        dataForm: {
          id: 0,
          name: '',
          listImg: '',
          categoryId: '',
          sort: '',
          status: '1',
        },
        //字段约束
        dataRule: {
          name: [
            { required: true, message: '板块名称不能为空', trigger: 'blur' }
          ],
          listImg: [
            { required: true, message: '板块图片不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id,categoryList,categoryId) {
        //设置图片上传地址
        this.uploadUrl = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/forum/community/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.name = data.community.name
                this.dataForm.listImg = data.community.listImg
                this.dataForm.sort = data.community.sort
                this.dataForm.status = data.community.status
              }
            })
          }
          this.categoryList = categoryList
          this.dataForm.categoryId = categoryId
        })

        // this.$http({
        //   url: this.$http.adornUrl(`/forum/communitycategory/all`),
        //   method: 'get',
        // }).then(({data}) => {
        //   this.categoryList = data.data
        // })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/forum/community/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'listImg': this.dataForm.listImg,
                'categoryId': this.dataForm.categoryId,
                'sort': this.dataForm.sort,
                'status': this.dataForm.status,
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      //上传成功回调函数
      handleAvatarSuccess(res, file) {
        this.dataForm.listImg = res.url
        this.imageUrl = URL.createObjectURL(file.raw);

        this.$message({
          message: '图片上传成功......',
          type: 'success'
        });
      },
      //上传前回调函数
      beforeAvatarUpload(file) {
        this.$message({
          message: '图片正在上传中......',
          type: 'warning'
        });
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      //上传失败回调函数
      handleAvatarError(){
        this.$message.error('文件上传失败,请重试!');
      }
    }
  }
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
